package com.health.mapp.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.health.db.dto.StuffDetailDto;
import com.health.db.model.MedicalTreatRecordTemp;
import com.health.db.model.PatientListTemp;
import com.health.db.model.RegisterOrder;
import com.health.db.model.RegisterOrderExample;
import com.health.db.model.RegisterOrderTemp;
import com.health.db.service.order.IRegisterOrderService;
import com.health.db.service.sm.IRongService;
import com.health.db.service.user.IStuffListService;
import com.health.db.service.user.IUserCardListService;
import com.health.mapp.bean.Header;
import com.health.mapp.bean.QueryOrderReq;
import com.health.mapp.bean.QueryOrderResp;
import com.health.mapp.utils.Constant;
import com.health.mapp.utils.DateUtils;
import com.health.mapp.utils.Response;
import com.health.mapp.utils.ResultCode;

/**
 *  订单查询类
 * @author HiRoad
 *
 */
public class QueryOrderImpl implements ActionInterface {
	private IRegisterOrderService registerOrderService  ;
	private IUserCardListService userCardListService;
	 private IStuffListService stuffListService  ;
	 
	 private IRongService rongService  ; 
	
	@Override
	public Response execute(Header header, Object reqBean) throws Exception {
		
		QueryOrderReq req=(QueryOrderReq) reqBean;
		QueryOrderResp _resp= new QueryOrderResp();
		
		String appId =   header.getAppId();
		RegisterOrderExample temp = new RegisterOrderExample();
		temp.setAppId(appId);
		//PageBean page = new PageBean(req.getPageNo(),req.getPageNum());
		
		Integer pageNo=req.getPageNo();
		Integer pageSize=req.getPageNum();
		
		if(null!=pageNo&&null!=pageSize){
			temp.setOffset((pageNo.intValue()-1)*pageSize.intValue());
			temp.setPageSize(pageSize.intValue());
		}
		//预订单Id
		 Long orderId =req.getOrderId();
		//订单类型
		 //int orderType =req.getOrderType();
		//医生编号
		 Long docId = req.getDocId();
		//用户编号
		 Long userId = req.getUserId();
		 String orderState = req.getOrderState();
		
		 //医生编号 用户编号 订单号 取一
		 if(orderId!=0){
			temp.setRegisterid(req.getOrderId());
		}else if(docId!=0){
			temp.setAccepterid(Long.valueOf(req.getDocId()));
			StuffDetailDto stuffDetailDto = stuffListService.selectByStuffId(docId);
			
			if (stuffDetailDto.getTypeid().intValue()==2) {
				/*StuffListExample example = new StuffListExample();
				example.setStuffAlias(String.valueOf(docId));
				List<StuffList> stuffLists = stuffListService.selectByExample(example);
				
				List<Long> accepterids = new ArrayList<Long>();
				
				for (int i = 0; i < stuffLists.size(); i++) {
					StuffList stuffTemp = stuffLists.get(i);
					accepterids.add(stuffTemp.getStuffid());
				}
				if (accepterids.size()!=0) {
					temp.setAccepterids(accepterids);
				}*/
				temp.setSsMeasure(String.valueOf(docId));
			}
			
			if (null!=stuffDetailDto) {
				String registerWhere = stuffDetailDto.getRegisterWhere();
				
				String[] runstatusids =Constant.CONSTANTS_COMMON_ORDER.split(",");
				List<Integer> commonOrderId = new ArrayList<Integer>();
				
				for (int i = 0; i < runstatusids.length; i++) {
					if (registerWhere.contains(runstatusids[i])) {
						commonOrderId.add(Integer.valueOf(runstatusids[i]));
					}
				}
				//避免排序混乱
				Collections.sort(commonOrderId);
				temp.setCommonOrderIds(commonOrderId);
			}else{
				_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3001);
				_resp.setErrorMsg("本订单入参医生无权接受");
				return _resp;
			}
		
			
		}else if(userId!=0){
			temp.setUserid(Long.valueOf(req.getUserId()));
		}else {
			_resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
			_resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);
			return _resp;
		}
		
		//单独查询还是复合查询
		if (StringUtils.isNotBlank(orderState)) {
			if (orderState.contains(",")) {
				
				 List<Integer> runstatusids = new ArrayList<Integer>();
				 String[] orders = orderState.split(",");
				 
				 for (int i = 0; i < orders.length; i++) {
					 runstatusids.add(Integer.valueOf(orders[i]));
				}
				//避免排序混乱
				 Collections.sort(runstatusids);
				 temp.setRunstatusids(runstatusids);
			}else{
				temp.setRunstatusid(Integer.valueOf(orderState));
			}
		}
		
	
		List<RegisterOrder> orderList =  registerOrderService.selectSimple(temp);
		
		
		//RegisterOrder transfer to RegisterOrderTemp
		List<RegisterOrderTemp> registerOrderList=new ArrayList<RegisterOrderTemp>();
		
		
		for(RegisterOrder order:orderList)
		{
			RegisterOrderTemp curr =new RegisterOrderTemp();
			curr.setAppOrderInfo("");
			curr.setContactTel(order.getUserContact());
			
			//doctor transfer
			curr.setFreeType(String.valueOf(order.getOrderfeetypeid()));
			curr.setOrderFee((order.getRegisterTotal())==null?"0":String.valueOf(order.getRegisterTotal()));
			curr.setOrderId(String.valueOf(order.getRegisterid()));
			curr.setOrderNumber(order.getRegisterNo());
			curr.setOrderState(String.valueOf(order.getRunstatusid()));
			curr.setOrderType(String.valueOf(order.getRegistertypeid()));
			curr.setRefBillId((order.getRefbillid())==null?"":String.valueOf(order.getRefbillid()));
			//patient Record transfer
			curr.setPayType(order.getPayTypeId()==null?null:String.valueOf(order.getPayTypeId()));
			
			curr.setCreateTime((order.getCreateDate())==null?"":DateUtils.formatDatetime(order.getCreateDate()).replace(" ", "T"));
			curr.setUpdateTime((order.getUpdateDate())==null?"":DateUtils.formatDatetime(order.getUpdateDate()).replace(" ", "T"));
			curr.setScheduleTime((order.getScheduleTime())==null?"":DateUtils.formatDatetime(order.getScheduleTime()).replace(" ", "T"));
			//user transfer
			curr.setUser(order.getUser());
			//curr.setPatRecord(order.getPatRecord());
			
			curr.setPatRecord(order.getPatRecord()==null?new MedicalTreatRecordTemp():order.getPatRecord());
			//curr.setDocId(String.valueOf(order.getAccepterid()));	
			
			if (null!=order.getDoctor()) {
				curr.setDoctor(order.getDoctor());
				curr.setDocId(order.getDoctor().getDocId());
			}else{
				curr.setDoctor(null);
			}
			
			if (null!=order.getiMsgIMMessageList()&&order.getiMsgIMMessageList().size()>0) {
				
				curr.setLastSendId(order.getiMsgIMMessageList().get(0).getSenderid().toString());
			}
			
			curr.setPatDescribe((order.getRegisterDesc())==null?"":order.getRegisterDesc());
			
			curr.setOrderTime((order.getScheduleDuration())==null?"0":String.valueOf(order.getScheduleDuration()));
			curr.setUserId(String.valueOf(order.getUserid()));
			
			curr.setPatRecordId(order.getPatRecordId()==null?"":String.valueOf(order.getPatRecordId()));
			curr.setGoodsIdNo(order.getGoodsIdno());
			curr.setGoodsName(order.getGoodsName());
			curr.setChannel(String.valueOf(order.getRegisterguideid()));
		
			if (null!=order.getRegisterTotal()) {
				curr.setPrice(String.valueOf(order.getRegisterTotal().setScale(2)));
			}
			//首尔送药，无patient,userName入patient
			if (Constant.CONSTANTS_ORDER_TYPE_ID_4.intValue()==order.getRegistertypeid().intValue()) {
				PatientListTemp patient = new PatientListTemp();
				patient.setPatName(order.getUser().getUserName());
				curr.setPatient(patient);
				curr.setPatId(null);
				curr.setCardType(order.getCardItemID());		
				
			}else{
				curr.setPatient(order.getPatient());
				curr.setPatId(String.valueOf(order.getPatientid()));
			}
			registerOrderList.add(curr);
		}
		
		_resp.setOrderInfoList(registerOrderList);
		_resp.setPageNo(pageNo);
		_resp.setPageNum(pageSize);
		_resp.setErrorCode(ResultCode.OPERATION_SUCCESS);
		_resp.setErrorMsg(ResultCode.OPERATION_SUCCESS_NOTE);
			 
		 if (req.getOrderId()!=0&&orderList.size()==1) {
			 Thread thread = new delayPublishGroupMsg(rongService,orderList.get(0));
		     thread.start();
		 }
		return _resp;
	}
	
	/**
	 * 线程启动
	 * @author HiRoad
	 *
	 */
	private class delayPublishGroupMsg extends Thread
	 {
		private IRongService rongService;
		private RegisterOrder registerOrder; 
		
	     public delayPublishGroupMsg(  IRongService rongService,RegisterOrder registerOrder ) {
			super();
		;
			this.rongService = rongService;
			this.registerOrder=registerOrder;
		}

		public void run()
	     {
			 try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			 rongService.PublishGroupMsg(registerOrder);
	     }
	 }
	
	

	public IRegisterOrderService getRegisterOrderService() {
		return registerOrderService;
	}

	public void setRegisterOrderService(IRegisterOrderService registerOrderService) {
		this.registerOrderService = registerOrderService;
	}

	/**
	 * @return the userCardListService
	 */
	public IUserCardListService getUserCardListService() {
		return userCardListService;
	}

	/**
	 * @param userCardListService the userCardListService to set
	 */
	public void setUserCardListService(IUserCardListService userCardListService) {
		this.userCardListService = userCardListService;
	}

	/**
	 * @return the stuffListService
	 */
	public IStuffListService getStuffListService() {
		return stuffListService;
	}

	/**
	 * @param stuffListService the stuffListService to set
	 */
	public void setStuffListService(IStuffListService stuffListService) {
		this.stuffListService = stuffListService;
	}

	public IRongService getRongService() {
		return rongService;
	}

	public void setRongService(IRongService rongService) {
		this.rongService = rongService;
	}

}
